package com.zxy.supplier_system.server.repository

import com.zxy.supplier_system.server.entity.Employee
import com.zxy.supplier_system.server.entity.EmployeeOperateRecord
import com.zxy.supplier_system.server.utils.SpecificationUtils
import com.zxy.supplier_system.server.utils.joinOnce
import org.springframework.data.jpa.domain.Specification
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.JpaSpecificationExecutor
import java.time.LocalDate
import java.time.OffsetDateTime

interface EmployeeOperateRecordRepository :JpaRepository<EmployeeOperateRecord,Int>,JpaSpecificationExecutor<EmployeeOperateRecord>{

    object Specifications{

        fun orderByCreatedDateTime(): Specification<EmployeeOperateRecord> {
            return Specification { root, query, criteriaBuilder ->
                query.orderBy(criteriaBuilder.desc(root.get<OffsetDateTime>("createdDateTime"))).restriction
            }
        }

        fun createdDateTimeGreaterThanOrEqualTo(startDate: OffsetDateTime?): Specification<EmployeeOperateRecord> {
            return Specification { root, _, criteriaBuilder ->
                startDate?.let {
                    criteriaBuilder.greaterThanOrEqualTo(root.get("createdDateTime"), it)
                }
            }
        }

        fun createdDateTimeLessThanOrEqualTo(endDate: OffsetDateTime?): Specification<EmployeeOperateRecord> {
            return Specification { root, _, criteriaBuilder ->
                endDate?.let {
                    criteriaBuilder.lessThanOrEqualTo(root.get("createdDateTime"), it)
                }
            }
        }

        fun nameContains(name: String?): Specification<EmployeeOperateRecord> {
            return SpecificationUtils.contains({
                it.joinOnce<EmployeeOperateRecord, Employee>("employee").get("name")
            }, name)
        }

        fun operatorIn(operatorIds: List<Int>): Specification<EmployeeOperateRecord> {
            return SpecificationUtils.`in`({ root ->
                root.joinOnce<EmployeeOperateRecord, Employee>("employee").get("id")
            }, operatorIds)
        }

    }

    fun deleteAllByCreatedDateTimeBefore(createdDateTimeBefore: OffsetDateTime): Int

}
